<template>
  <div>
    <div :class="{ 'cover-wrap': true, 'bg': (value ? 'true': 'false') }" @click="show()">
      <img :src="value" class="cover-image" ref="cover-image" alt="" />
    </div>
    <el-dialog title="素材库" :visible.sync="dialogVisible" append-to-body>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="first">
          <image-list
            :is-show-add="false"
            :is-show-action="false"
            :is-show-selected="true"
            :is-publish="true"
            ref="image-list"
          ></image-list>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="second">
          <input
            type="file"
            name=""
            id=""
            @change="onFileChange()"
            ref="file"
          />
          <img width="100" src="" alt="" ref="preview-image" />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onCoverConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { uploadImage } from '@/api/image'
import ImageList from '../../image/components/image-list'
export default {
  name: 'UploadCover',
  props: ['value'],
  components: {
    'image-list': ImageList
  },
  data() {
    return {
      dialogVisible: false,
      activeName: 'first'
    }
  },
  created() {},
  methods: {
    show() {
      this.dialogVisible = true
    },
    onFileChange() {
      const file = this.$refs.file.files[0]
      const blob = window.URL.createObjectURL(file)
      this.$refs['preview-image'].src = blob
    },
    onCoverConfirm() {
      if (this.activeName === 'second') {
        const file = this.$refs.file.files[0]
        if (!file) {
          this.$message.error('请选择文件！')
          return false
        }
        const fd = new FormData()
        fd.append('image', file)
        uploadImage(fd).then((res) => {
          this.dialogVisible = false
          this.$refs['cover-image'].src = res.data.data.url
          this.$emit('input', res.data.data.url)
        })
      } else if (this.activeName === 'first') {
        const imageList = this.$refs['image-list']
        const selected = imageList.selected
        if (selected === null) {
          this.$message.error('请选择封面图片')
          return false
        }
        this.dialogVisible = false
        this.$emit('input', imageList.images[selected].url)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.cover-wrap {
  width: 150px;
  height: 150px;
  border: 1px solid #ddd;
  margin-right: 15px;
  .cover-image {
    height: 150px;
    width: 150px;
  }
}
.bg {
  background: url('./add.jpg') no-repeat;
  background-size: cover;
}
</style>
